package com.cqemme.comm.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@SuppressWarnings({"ALL", "AlibabaConstantFieldShouldBeUpperCase"})
@Slf4j
public class MD5Utils {
	private static final String[] hexDigIts  = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
	private static final String charset = "utf-8";
    /**
     * MD5加密
     * @param origin 字符
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String MD5Encode(String origin, String charsetName) {
        String resultString = null;
        try{
            MessageDigest md = MessageDigest.getInstance("MD5");
            if(StringUtils.checkIsNullsOne(charsetName)){
                resultString = byteArrayToHexString(md.digest(origin.getBytes()));
            }else{
                resultString = byteArrayToHexString(md.digest(origin.getBytes(charsetName)));
            }
        }catch (NoSuchAlgorithmException e){
            log.error(e.getMessage());
        }catch (UnsupportedEncodingException e) {
        	 log.error(e.getMessage());
		}
        return resultString;
    }
    
    /**
     * MD5加密
     * @param origin 字符
     * @return
     */
    public static String MD5Encode(String origin){
        String resultString = null;
        try{
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(origin.getBytes(charset)));
        }catch (NoSuchAlgorithmException e){
            log.error(e.getMessage());
        }catch (UnsupportedEncodingException e) {
        	 log.error(e.getMessage());
		}
        return resultString;
    }
    /**
     * MD5加密
     * @param origin 字节信息
     * @return
     */
    public static String MD5Encode(byte[] origin){
        String resultString = null;
        try{
            MessageDigest md = MessageDigest.getInstance("MD5");
            resultString = byteArrayToHexString(md.digest(origin));
        }catch (NoSuchAlgorithmException e){
            log.error(e.getMessage());
        }
        return resultString;
    }
    public static String byteArrayToHexString(byte[] b){
        StringBuffer resultSb = new StringBuffer();
        for(int i = 0; i < b.length; i++){
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    public static String byteToHexString(byte b){
        int n = b;
        if(n < 0){
            n += 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigIts[d1] + hexDigIts[d2];
    }
    public static boolean matchesPwdByMd5(String encodedPassword, String rawPassword) {
			if (!StringUtils.isBlank(encodedPassword) && !StringUtils.isBlank(rawPassword)) {
				if (encodedPassword.equalsIgnoreCase(MD5Encode(rawPassword))) {
					return true;
				}
			}
		return false;
	}
}
